package September29;

import java.io.*;

public class FileEncryptorDecryptor {

    public static void encryptDecryptFile(String filePath, boolean isEncrypt) {
        File inputFile = new File(filePath);
        if (!inputFile.exists()) {
            System.out.println("文件不存在");
            return;
        }

        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(filePath + ".tmp");
             FileInputStream fisTmp = new FileInputStream(filePath + ".tmp");
             FileOutputStream fosFinal = new FileOutputStream(inputFile)) {

            int byteRead;
            while ((byteRead = fis.read()) != -1) {
                byte modifiedByte = (byte) (isEncrypt ? ~byteRead : ~byteRead);
                fos.write(modifiedByte);
            }

            // 重置流的位置
            fisTmp.getChannel().position(0);

            while ((byteRead = fisTmp.read()) != -1) {
                fosFinal.write(byteRead);
            }

            // 删除临时文件
            new File(filePath + ".tmp").delete();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String fileName = "example.txt"; // 替换为你的文件名

        // 加密文件
        encryptDecryptFile(fileName, true);

        // 解密文件
        encryptDecryptFile(fileName, false);
    }
}
